package com.xbongbong.pay.platform.wechatpay.client;

import com.wechat.pay.contrib.apache.httpclient.WechatPayHttpClientBuilder;
import com.wechat.pay.contrib.apache.httpclient.auth.AutoUpdateCertificatesVerifier;
import com.wechat.pay.contrib.apache.httpclient.auth.PrivateKeySigner;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Credentials;
import com.wechat.pay.contrib.apache.httpclient.auth.WechatPay2Validator;
import org.apache.http.impl.client.CloseableHttpClient;

import java.security.PrivateKey;

public class WeChatClient {
    /**
     * Description: WeChat HTTPclient 初始化
     * @param privateKey
     * @param mchId
     * @param mchSerialNo
     * @param apiV3Key
     * @return org.apache.http.client.HttpClient
     * @author 魏荣杰
     * @date 2021/1/11 11:30
     */
    public static CloseableHttpClient build(PrivateKey privateKey, String mchId, String mchSerialNo, String apiV3Key) throws Exception{
        // 加载商户私钥（privateKey：私钥字符串）
//        PrivateKey merchantPrivateKey = PemUtil.loadPrivateKey(new ByteArrayInputStream(privateKey.getBytes("utf-8")));

        // 加载平台证书（mchId：商户号,mchSerialNo：商户证书序列号,apiV3Key：V3秘钥）
        AutoUpdateCertificatesVerifier verifier = new AutoUpdateCertificatesVerifier(
                new WechatPay2Credentials(mchId, new PrivateKeySigner(mchSerialNo, privateKey)), apiV3Key.getBytes("utf-8"));

        // 初始化httpClient
        return WechatPayHttpClientBuilder.create()
                .withMerchant(mchId, mchSerialNo, privateKey)
                .withValidator(new WechatPay2Validator(verifier)).build();
    }

}
